﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using WeifenLuo.WinFormsUI.Base;

namespace HRM
{
    public partial class FormManualTimeSheet : FormBaseDataGrid
    {
        private Ctrl_General mCtrlGeneral;
        private DataSet mdsTimeSheet;
        private SqlDataAdapter mdaTimeSheetUpdate;

        public FormManualTimeSheet()
        {
            InitializeComponent();
        }

        protected override void BasicForm_Load(object sender, EventArgs e)
        {
            base.BasicForm_Load(sender, e);
        }

        protected override void BaseForm_Activated(object sender, System.EventArgs e)
        {
            base.BaseForm_Activated(sender, e);
        }

        protected override void BaseForm_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
        {
            base.BaseForm_KeyDown(sender, e);
        }

        protected override void BasicForm_Closing(object sender, System.Windows.Forms.FormClosingEventArgs e)
        {
            base.BasicForm_Closing(sender, e);
        }

        #region Override LoadMasterData
        protected override void LoadMasterData()
        {
            try
            {
                btnCancel = btncancel;
                btnOk = btnok;
                lblStatus = lblstatus;
                // default month, year
                cboYear.Text = DateTime.Now.Year.ToString();
                cboMonth.Text = (DateTime.Now.Month.ToString().Length == 1 ? "0" + DateTime.Now.Month.ToString() : DateTime.Now.Month.ToString());

                LoadData();
                btnImport.Enabled = false;
            }
            catch (Exception ex)
            {
                MessageBox.Show("Cannot load Manual Time Sheet Form'. Error: '" + ex.Message + "'", ConstantKeys.Title, MessageBoxButtons.OK, MessageBoxIcon.Stop);
            }
        }
        #endregion

        #region LoadData method
        private void LoadData()
        {
            try
            {
                Cursor = Cursors.WaitCursor;
                if (mCtrlGeneral == null) mCtrlGeneral = new Ctrl_General();

                string lCondiction = " Where TS.Years = " + cboYear.Text.Trim() + " and TS.Months = " + cboMonth.Text.Trim() + " Order By TS.ID_Emp ";
                string lCondiction1 = " Years = " + cboYear.Text.Trim() + " and Months = " + cboMonth.Text.Trim() + " Order By ID_Emp ";

                string ls_SQL = "Select TS.ID_Emp, PF.Emp_NameVN, TS.Years, TS.Months,"
                    + " TS.d1, TS.d2, TS.d3, TS.d4, TS.d5, TS.d6, TS.d7, TS.d8, TS.d9, TS.d10, TS.d11, TS.d12, TS.d13, TS.d14, TS.d15,"
                    + " TS.d16, TS.d17, TS.d18, TS.d19, TS.d20, TS.d21, TS.d22, TS.d23, TS.d24, TS.d25, TS.d26, TS.d27, TS.d28, TS.d29, TS.d30, TS.d31, TS.Note, "
                    + "TS.CreatedUser, TS.UpdatedUser, TS.CreatedDate, TS.UpdatedDate "
                    + "From HRM_PersonnelManualTimeSheet TS inner join HRM_PersonalProfile PF on TS.ID_Emp = PF.ID_Emp "
                    + lCondiction;

                mdsTimeSheet = mCtrlGeneral.GetSelect(ls_SQL, "HRM_PersonnelManualTimeSheet");
                mCtrlGeneral.GetDataWithCondition(out mdaTimeSheetUpdate, "HRM_PersonnelManualTimeSheet", lCondiction1);

                if (mdsTimeSheet == null) return;
                mdbg_dataGrid.DataSource = mdsTimeSheet;
                mdbg_dataGrid.DataMember = "HRM_PersonnelManualTimeSheet";

                /////////////////////// Build Day Of Week /////////////////////////////////////////////////////////////////
                string ls_SQLPeriod = "select Top 2 Starting_Date From dbo.HRM_Period Where convert(varchar(8), Starting_Date, 112) >= '" + cboYear.Text.Trim() + cboMonth.Text.Trim() + "01" + "' Order By Starting_Date ";
                DataSet ldsPeriod = mCtrlGeneral.GetSelect(ls_SQLPeriod, "HRM_Period");

                if (ldsPeriod.Tables[0].Rows.Count == 2)
                {
                    string dt2 =DateTime.Parse(ldsPeriod.Tables[0].Rows[1]["Starting_Date"].ToString()).ToString("yyyy/MM/dd");
                    string dt1 = DateTime.Parse(ldsPeriod.Tables[0].Rows[0]["Starting_Date"].ToString()).ToString("yyyy/MM/dd");
                    double ldays = (DateTime.Parse(dt2) - DateTime.Parse(dt1)).TotalDays;
                    int j = 4;
                    DateTime dt;
                    mdbg_dataGrid.EnableHeadersVisualStyles = false;
                    for (int i = 0; i < ldays; i++)
                    {
                        int year = DateTime.Parse(dt1).AddDays(i).Year;
                        int month= DateTime.Parse(dt1).AddDays(i).Month;
                        int days = DateTime.Parse(dt1).AddDays(i).Day;
                        dt = new DateTime(year, month, days);
                        mdbg_dataGrid.Columns[j].HeaderText = dt.DayOfWeek + " (" + dt.Date.ToShortDateString() + ") ";
                        if (dt.DayOfWeek == DayOfWeek.Saturday)
                        {
                            mdbg_dataGrid.Columns[j].HeaderCell.Style.BackColor = Color.Pink;
                            mdbg_dataGrid.Columns[j].DefaultCellStyle.BackColor = Color.Pink;
                        }
                        else if (dt.DayOfWeek == DayOfWeek.Sunday)
                        {
                            mdbg_dataGrid.Columns[j].HeaderCell.Style.BackColor = Color.Red;
                            mdbg_dataGrid.Columns[j].DefaultCellStyle.BackColor = Color.Red;
                        }
                        else
                        {
                            mdbg_dataGrid.Columns[j].HeaderCell.Style.BackColor = SystemColors.Control;
                            mdbg_dataGrid.Columns[j].DefaultCellStyle.BackColor = SystemColors.Window;
                        }

                        j++;
                    }

                    for (int z = (int)ldays+ 1; z <= 31; z++)
                    {
                        mdbg_dataGrid.Columns["d" + z.ToString()].Visible = false;
                    }

                }
                ////////////////////////////////////////////////////////////////////////////////////////////////////////////


                mRowManager = (CurrencyManager)mdbg_dataGrid.BindingContext[mdsTimeSheet, "HRM_PersonnelManualTimeSheet"];
                // How to refresh the status of the row position?Ordinal_Number
                mRowManager.PositionChanged += new EventHandler(RowMaster_Changed);

                base.LoadMasterData();
                Cursor = Cursors.Default;
            }
            catch (Exception ex)
            {
                MessageBox.Show("Manual Time Sheet Form'. Error: '" + ex.Message + "'", ConstantKeys.Title, MessageBoxButtons.OK, MessageBoxIcon.Error);
                Ctrl_LOG.Print("Manual Time Sheet Form", "LoadData() method", "Error: " + ex.Message);
                Cursor = Cursors.Default;
            }
        }
        #endregion

        #region save
        public override void save()
        {
            try
            {
                if (mdsTimeSheet == null) return;
                mRowManager.EndCurrentEdit();
                if (!mdsTimeSheet.HasChanges())
                {
                    base.save();
                    return;
                }
                DataSet ldsHasChanged = mdsTimeSheet.GetChanges();
                foreach (DataRow dr in ldsHasChanged.Tables[0].Rows)
                {
                    if (dr.RowState == DataRowState.Deleted) continue;
                    if (dr.RowState == DataRowState.Added)
                    {
                        dr["CreatedDate"] = DateTime.Now;
                        dr["CreatedUser"] = mMainForm.ms_UserID;
                        dr["Years"] = cboYear.Text.Trim();
                        dr["Months"] = cboMonth.Text;
                    }
                    else if (dr.RowState == DataRowState.Modified)
                    {
                        //dr["DayOfWeek"] = DateTime.Parse(dr["Wrk_Date"].ToString()).DayOfWeek;
                        dr["UpdatedDate"] = DateTime.Now;
                        dr["UpdatedUser"] = mMainForm.ms_UserID;
                    }
                }
                string ls_ColName = "", ls_TableName = "";
                string ls_Error = mCtrlGeneral.Update(mdaTimeSheetUpdate, ldsHasChanged, "HRM_PersonnelManualTimeSheet", out ls_ColName, out ls_TableName);
                if (ls_Error == "")
                {
                    mdsTimeSheet.AcceptChanges();
                    int li_pos = 0;
                    if (GetCurrentAction() == MODES.MODIFY) li_pos = mRowManager.Position;
                    LoadData();
                    if (li_pos > 0) mRowManager.Position = li_pos;
                    base.save();
                    btnBrowse.Enabled = true;
                    btnImport.Enabled = false;
                }
                else
                {
                    MessageBox.Show("Cannot save Manual Time Sheet data'. Error: '" + ls_Error + "'", ConstantKeys.Title, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("DB Error: " + ex.Message, ConstantKeys.Title, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        #endregion

        #region cancel
        public override void cancel()
        {
            mdbg_dataGrid.Focus();
            if (mdsTimeSheet == null) return;
            mRowManager.EndCurrentEdit();
            mdsTimeSheet.RejectChanges();
            base.cancel();
            btnBrowse.Enabled = true;
            if(!lblFilePath.Text.Trim().Equals("")) btnImport.Enabled = false;
        }
        #endregion

        #region add
        public override void add()
        {
            mdbg_dataGrid.Focus();
            base.add();
            btnBrowse.Enabled = false;
            btnImport.Enabled = false;
        }
        #endregion

        #region modify
        public override void modify()
        {
            base.modify();
            btnBrowse.Enabled = false;
            btnImport.Enabled = false;
        }
        #endregion

        #region delete
        public override void delete()
        {
            base.delete();
            if (!mb_AcceptDelete) return;
            DataSet ldsDelete = (DataSet)mdbg_dataGrid.DataSource;
            DataRow ldrDelete = ldsDelete.Tables[0].Rows[mRowManager.Position];
            ldrDelete.Delete();
            string lsColName = "", lsTableName = "";
            string lsReturnMessage = mCtrlGeneral.Update(mdaTimeSheetUpdate, ldsDelete, "HRM_PersonnelManualTimeSheet", out lsColName, out lsTableName);
            if (lsReturnMessage != "")
            {
                MessageBox.Show("Cannot delete Manual Time Sheet data'. Error: '" + lsReturnMessage + "'", ConstantKeys.Title, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                ldsDelete.RejectChanges();
                ldsDelete.AcceptChanges();
            }
        }
        #endregion

        private void btnok_Click(object sender, System.EventArgs e)
        {
            save();
        }

        private void btncancel_Click(object sender, System.EventArgs e)
        {
            cancel();
        }

        private void btnBrowse_Click(object sender, EventArgs e)
        {
            string lFilePath = "";
            if (!mCtrlGeneral.GetPathOpenFileDlg(out lFilePath))
                MessageBox.Show("Cannot get 'Time Sheet' file path. Error message: '" + lFilePath + "'", ConstantKeys.Title, MessageBoxButtons.OK, MessageBoxIcon.Error);
            else
            {
                lblFilePath.Text = lFilePath;
                btnImport.Enabled = true;
            }
        }

        #region CellValueChanged Event
        private void mdbg_dataGrid_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            /*if (GetCurrentAction() == MODES.FULL || GetCurrentAction() == MODES.VOID) return;
            string ls_SQL = String.Empty;
            string ls_IDEmp = mdbg_dataGrid["ID_Emp", e.RowIndex].Value.ToString();
            string lsWrkDate = mdbg_dataGrid["Wrk_Date", e.RowIndex].Value.ToString();
            if (lsWrkDate.Equals(""))
                lsWrkDate = DateTime.Now.ToString("yyyy/MM/dd");
            else
               lsWrkDate = DateTime.Parse(mdbg_dataGrid["Wrk_Date", e.RowIndex].Value.ToString()).ToString("yyyy/MM/dd");

            DataSet lds;

            if (e.ColumnIndex == 0)
            {
                lds = mCtrlGeneral.GetSelect(" Select Emp_NameVN, FollowTimeAtt From HRM_PersonalProfile Where ID_Emp = '" + ls_IDEmp + "'", "HRM_PersonalProfile");
                mdbg_dataGrid["Emp_NameVN", e.RowIndex].Value = lds.Tables[0].Rows[0]["Emp_NameVN"];
                ////
                ls_SQL = "select PS.ID_Shift, DS.Shift_Name, DS.Begin_Hrs, DS.End_Hrs "
                        + " From dbo.HRM_PersonnelShift PS inner join dbo.HRM_DefineShift DS on PS.ID_Shift = DS.ID_Shift "
                        + " where PS.ID_Emp = '" + ls_IDEmp + "' "
                        + " and Convert(varchar(8), PS.Begin_Date, 112) <= Convert(varchar(8), Convert(Datetime, '" + lsWrkDate + "'), 112) "
                        + " and Convert(varchar(8), PS.End_Date, 112) >=Convert(varchar(8), Convert(Datetime, '" + lsWrkDate + "'), 112) ";
                lds = mCtrlGeneral.GetSelect(ls_SQL, "HRM_PersonnelShift");
                if (lds.Tables[0].Rows.Count > 0)
                {
                    mdbg_dataGrid["ID_Shift", e.RowIndex].Value = lds.Tables[0].Rows[0]["ID_Shift"];
                    mdbg_dataGrid["Shift_Name", e.RowIndex].Value = lds.Tables[0].Rows[0]["Shift_Name"];
                    mdbg_dataGrid["Begin_Hrs", e.RowIndex].Value = lds.Tables[0].Rows[0]["Begin_Hrs"];
                    mdbg_dataGrid["End_Hrs", e.RowIndex].Value = lds.Tables[0].Rows[0]["End_Hrs"];
                    mdbg_dataGrid["Time_In", e.RowIndex].Value = lds.Tables[0].Rows[0]["Begin_Hrs"];
                    mdbg_dataGrid["Time_Out", e.RowIndex].Value = lds.Tables[0].Rows[0]["End_Hrs"];
                    
                }
            }
            else if (e.ColumnIndex == 2)
            {
                ls_SQL = "select PS.ID_Shift, DS.Shift_Name, DS.Begin_Hrs, DS.End_Hrs "
                        + " From dbo.HRM_PersonnelShift PS inner join dbo.HRM_DefineShift DS on PS.ID_Shift = DS.ID_Shift "
                        + " where PS.ID_Emp = '" + ls_IDEmp + "' "
                        + " and Convert(varchar(8), PS.Begin_Date, 112) <= Convert(varchar(8), Convert(Datetime, '" + lsWrkDate + "'), 112) "
                        + " and Convert(varchar(8), PS.End_Date, 112) >= Convert(varchar(8), Convert(Datetime, '" + lsWrkDate + "'), 112) ";
                lds = mCtrlGeneral.GetSelect(ls_SQL, "HRM_PersonnelShift");
                if (lds.Tables[0].Rows.Count > 0)
                {
                    mdbg_dataGrid["ID_Shift", e.RowIndex].Value = lds.Tables[0].Rows[0]["ID_Shift"];
                    mdbg_dataGrid["Shift_Name", e.RowIndex].Value = lds.Tables[0].Rows[0]["Shift_Name"];
                    mdbg_dataGrid["Begin_Hrs", e.RowIndex].Value = lds.Tables[0].Rows[0]["Begin_Hrs"];
                    mdbg_dataGrid["End_Hrs", e.RowIndex].Value = lds.Tables[0].Rows[0]["End_Hrs"];
                    mdbg_dataGrid["Time_In", e.RowIndex].Value = lds.Tables[0].Rows[0]["Begin_Hrs"];
                    mdbg_dataGrid["Time_Out", e.RowIndex].Value = lds.Tables[0].Rows[0]["End_Hrs"];
                    
                }
            }*/
        }
        #endregion

        private void btnLoad_Click(object sender, EventArgs e)
        {

        }

        #region Override DataGridView Keyup event
        protected override void mdbg_dataGrid_KeyUp(object sender, KeyEventArgs e)
        {
            if (GetCurrentAction() == MODES.FULL || GetCurrentAction() == MODES.VOID) return;
            if (e.KeyCode != Keys.F9) return;
            OpenSelection(mdbg_dataGrid.Columns[mdbg_dataGrid.CurrentCell.ColumnIndex].Name);
        }
        #endregion

        #region Open selection
        public override void OpenSelection(string as_SelectioField)
        {
            SelectionParam lstr_param = new SelectionParam();
            lstr_param.ms_SelectionField = as_SelectioField;
            FormSelection lfrmSelect = new FormSelection();
            lfrmSelect.mfrmParentForm = this;
            lfrmSelect.Owner = mMainForm;

            switch (as_SelectioField)
            {
                 case "ID_Emp":
                    lstr_param.ms_SelectionName = "Personnel Profile";
                    lfrmSelect.SetParam(lstr_param);
                    if (lfrmSelect.ShowDialog() == DialogResult.OK)
                    {
                        string[] astrID = lfrmSelect.GetParam().msa_ReturnValues[0].Split(',');
                        string[] astrName = lfrmSelect.GetParam().msa_ReturnValues[1].Split(',');
                        if (astrID.Length == 1)
                        {
                            mdbg_dataGrid["ID_Emp", mdbg_dataGrid.CurrentCell.RowIndex].Value = lfrmSelect.GetParam().msa_ReturnValues[0];
                            mdbg_dataGrid["Emp_NameVN", mdbg_dataGrid.CurrentCell.RowIndex].Value = lfrmSelect.GetParam().msa_ReturnValues[1];
                        }
                        else
                        {   // Assign first value for current row
                            mdbg_dataGrid["ID_Emp", mdbg_dataGrid.CurrentCell.RowIndex].Value = astrID[0];
                            mdbg_dataGrid["Emp_NameVN", mdbg_dataGrid.CurrentCell.RowIndex].Value = astrName[0];

                            // Assign next value for new row
                            DataRow dr;
                            for (int i = 1; i < astrID.Length; i++)
                            {
                                dr = mdsTimeSheet.Tables[0].NewRow();
                                dr["ID_Emp"] = astrID[i];
                                dr["Emp_NameVN"] = astrName[i];
                                mdsTimeSheet.Tables[0].Rows.Add(dr);
                            }
                        }
                    } break;
            }
        }
        #endregion

        private void btnFilter_Click(object sender, EventArgs e)
        {
            mdbg_dataGrid.ResumeLayout(true);
            LoadData();
        }

        private void btnTemplate_Click(object sender, EventArgs e)
        {
            try
            {
                Cursor = Cursors.WaitCursor;
                CreateExcelDoc excell_app = new CreateExcelDoc();
                //creates text header for excel file
                string lsMsg = excell_app.ExportDGV2XLSX(1, 1, mdbg_dataGrid);
                if (!lsMsg.Equals("")) MessageBox.Show("Cannot export Manual Time Sheet template. Error message: " + lsMsg, ConstantKeys.Title, MessageBoxButtons.OK, MessageBoxIcon.Error);
                Cursor = Cursors.Default;
            }
            catch (Exception ex)
            {
                MessageBox.Show("Cannot get Manual Time Sheet template. Error message: " + ex.Message, ConstantKeys.Title, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                Cursor = Cursors.Default;
            }
        }

        private void btnImport_Click(object sender, EventArgs e)
        {
            try
            {
                Cursor = Cursors.WaitCursor;
                CreateExcelDoc excell_app = new CreateExcelDoc();
                base.add();
                // build defalt values
                Dictionary<string, object> dict = new Dictionary<string, object>();
                dict.Add("Years", cboYear.Text.Trim());
                dict.Add("Months", cboMonth.Text);
                dict.Add("CreatedUser", mMainForm.ms_UserID);
                dict.Add("CreatedDate", DateTime.Now);
                dict.Add("UpdatedUser", null);
                dict.Add("UpdatedDate", DateTime.MaxValue);
                // Import data from excel file to grid
                excell_app.ImportXLSX2DGV(lblFilePath.Text, mdbg_dataGrid, dict);
                Cursor = Cursors.Default;
            }
            catch (Exception ex)
            {
                MessageBox.Show("Cannot import Manual Time Sheet from excel file. Error message: " + ex.Message, ConstantKeys.Title);
            }
            finally
            {
                Cursor = Cursors.Default;
            }
        }
    }
}
